#!/usr/bin/python
# -*- coding: utf-8 -*-

#为方便以后移植，参数中的 key 一律为字符串格式
import datetime
import math

import geobox
import logging

from google.appengine.ext import db
from google.appengine.api import memcache 
from google.appengine.api import users

from django.conf import settings

from common import commonfunction
import googledatabase
import getcounter
import function_public

#===================================== 云：推荐、收藏 =============================================
CLOUD_ID_COUNT_NAME = 'CloudIDCount'


#获得一个搜索关键字记录
def GetOneSearchKeyItem(TagName):
    if 1 > len(TagName):
        return None

    Query = db.GqlQuery( 'SELECT * FROM CSearchKeyTable WHERE TagName = :1', TagName )
    return Query.get()

#增加一个搜索关键字的搜索次数（没有就添加）
def AddOneSearchKeyNumber(TagName, Language):
    OneSearchKey = GetOneSearchKeyItem(TagName)
    if None == OneSearchKey:
        OneSearchKey = CSearchKeyTable()
        OneSearchKey.TagName = TagName
        OneSearchKey.TagLanguage = Language
        CSearchKeyTable.SearchNumber = 1
        return CSearchKeyTable.put()
    else:
        db.run_in_transaction(function_public.AddOnePropertyCount, OneSearchKey.key(), 'SearchNumber', 1)

#获得用户检索最多的关键字
#返回： 结果集
def GetHotCommendRecord(PageSize, Language=''):
    Query = None
    if '' == Language:
        Query = db.GqlQuery('SELECT * FROM CSearchKeyTable ORDER BY SearchNumber DESC')
    else:
        Query = db.GqlQuery('SELECT * FROM CSearchKeyTable WHERE TagLanguage = :1 ORDER BY SearchNumber DESC', Language)
        
    return Query.fetch(PageSize)


#按标签名获得一个用户可见的标签
#语言为 ‘’ 则获得所有语言的（主要的区别在系统标签）
#def GetOneUserTags(LoginID, Language = '', IncludeSystem = True):
#    Query = None
#    if IncludeSystem:
#        if '' == Language:
#            Query = db.GqlQuery( 'SELECT * FROM CTagTable WHERE (LoginID = '' OR LoginID = :1) ORDER BY TagName', LoginID )
#        else:
#            Query = db.GqlQuery( 'SELECT * FROM CTagTable WHERE (LoginID = '' OR LoginID = :1) AND TagLanguage = :2 ORDER BY TagName', LoginID, Language )
#    else:
#        if '' == Language:
#            Query = db.GqlQuery( 'SELECT * FROM CTagTable WHERE LoginID = :1 ORDER BY TagName', LoginID )
#        else:
#            Query = db.GqlQuery( 'SELECT * FROM CTagTable WHERE LoginID = :1 AND TagLanguage = :2 ORDER BY TagName', LoginID, Language )
#        
#    return Query.fetch(1000)

#获得用户推荐最多的云记录集
#返回： 结果集
def GetHotCommendRecord(PageSize):
    Query = db.GqlQuery('SELECT * FROM CCloudTable ORDER BY CommendNumber DESC')
    return Query.fetch(PageSize)


#获得用户收藏最多的云记录集
#返回： 结果集
def GetHotCollectRecord(PageSize):
    Query = db.GqlQuery('SELECT * FROM CCloudTable ORDER BY CollectNumber DESC')
    return Query.fetch(PageSize)


#获得一个云记录
def GetOneCloudItem(SourceUrl):
    if 1 > len(SourceUrl):
        return None

    Query = db.GqlQuery( 'SELECT * FROM CCloudTable WHERE SourceUrl = :1', SourceUrl )
    return Query.get()

#返回一个 Cloud 的 key
def SetOneCloudItem(SourceUrl, Title, TagList, Summary, IsCommend=True):
    User = users.get_current_user()
    if User is None:
        return None

    OneCloud = GetOneCloudItem(SourceUrl)
    if None == OneCloud:
        OneCloud = googledatabase.CCloudTable()
        OneCloud.ID = getcounter.GetAutoIncrementCount(CLOUD_ID_COUNT_NAME)
        OneCloud.SourceUrl = SourceUrl
        OneCloud.Title = Title
        OneCloud.TagList = TagList
        OneCloud.Summary = Summary[0:250]
        if IsCommend:
            OneCloud.FirstCommend = OneCloud.LastCommend = User
            OneCloud.CommendNumber = 1
        else:
            OneCloud.FirstCollect = OneCloud.LastCollect = User
            OneCloud.CollectNumber = 1

        RetKey = OneCloud.put()
        
        #清理缓存区数据
        memcache.delete('CCloudTable_New')
        memcache.delete('CCloudTable_PrePage')
        memcache.delete('CCloudTable_NextPage')
    
        return RetKey
    else:
        if IsCommend:
            OneCloud.LastCommend = User
            OneCloud.put()
            db.run_in_transaction(function_public.AddOnePropertyCount, OneCloud.key(), 'CommendNumber', 1)
        else:
            OneCloud.LastCollect = User
            OneCloud.put()
            db.run_in_transaction(function_public.AddOnePropertyCount, OneCloud.key(), 'CollectNumber', 1)
             
        return OneCloud.key()


#分页、逆时获得一个用户的收藏内容
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneUserCollectRecord(UserLoginID, PageSize, TimeDelta, TagDate = ''):
    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM CMyCollectTable WHERE LoginID = :1 AND Date > :2 ORDER BY Date',
                             UserLoginID, commonfunction.GetDatetimeFromString(TagDate) )
        Results = Query.fetch(PageSize)
        logging.debug( "--------------------- CollectRecord 1: len(Results) = %d" % (len(Results)) )
        if Results:
            PrePageTag = str(Results[len(Results) - 1].Date)
#    logging.debug( "--------------------- CollectRecord: TagDate = %s, PrePageTag = %s" % (TagDate, PrePageTag) )

    #计算下一页起始ID
    Query = db.GqlQuery( 'SELECT * FROM CMyCollectTable WHERE LoginID = :1 ORDER BY Date DESC', UserLoginID )
    if 0 < len(TagDate):
        Query = db.GqlQuery( 'SELECT * FROM CMyCollectTable WHERE LoginID = :1 AND Date <= :2 ORDER BY Date DESC',
                             UserLoginID, commonfunction.GetDatetimeFromString(TagDate) )
    Results = Query.fetch(PageSize + 1)
#    logging.debug( "--------------------- CollectRecord 2: len(Results) = %d" % (len(Results)) )
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].Date)
        Results = Results[:PageSize]

    #修正时间
    for Item in Results:
        Item.Date += TimeDelta

    return Results, PrePageTag, NextPageTag


#分页、顺时获得一个云推荐的评论内容
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneCommendCommentOnRecord(SourceUrl, PageSize, TimeDelta, TagDate = ''):
    OneCloud = GetOneCloudItem(SourceUrl)
    if None == OneCloud:
        return None, '', ''
    
    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagDate):
        Query = db.GqlQuery( "SELECT * FROM CMyCommendTable WHERE HaveCommentOn = True AND CloudKey = :1 AND Date < :2 ORDER BY Date DESC",
                             OneCloud.key(), commonfunction.GetDatetimeFromString(TagDate) )
        Results = Query.fetch(PageSize)
        logging.debug( "--------------------- CollectRecord 1: len(Results) = %d" % (len(Results)) )
        if Results:
            PrePageTag = str(Results[len(Results) - 1].Date)
#    logging.debug( "--------------------- CollectRecord: TagDate = %s, PrePageTag = %s" % (TagDate, PrePageTag) )
            
    #计算下一页起始ID
    Query = db.GqlQuery( "SELECT * FROM CMyCommendTable WHERE HaveCommentOn = True AND CloudKey = :1 ORDER BY Date", OneCloud.key() )
    if 0 < len(TagDate):
        Query = db.GqlQuery( "SELECT * FROM CMyCommendTable WHERE HaveCommentOn = True AND CloudKey = :1 AND Date >= :2 ORDER BY Date",
                             OneCloud.key(), commonfunction.GetDatetimeFromString(TagDate) )
    Results = Query.fetch(PageSize + 1)
#    logging.debug( "--------------------- CollectRecord 2: len(Results) = %d" % (len(Results)) )
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].Date)
        Results = Results[:PageSize]

    #修正时间
    for Item in Results:
        Item.Date += TimeDelta

    return Results, PrePageTag, NextPageTag


#分页、顺时获得一个云收藏的评论内容
#返回： 结果集, 前一页起始TagID, 后一页起始TagID
def GetOneCollectCommentOnRecord(SourceUrl, PageSize, TimeDelta, TagDate = ''):
    OneCloud = GetOneCloudItem(SourceUrl)
    if None == OneCloud:
        return None, '', ''
    
    #计算上一页起始ID
    PrePageTag = ''
    if 0 < len(TagDate):
        Query = db.GqlQuery( "SELECT * FROM CMyCollectTable WHERE HaveCommentOn = True AND CloudKey = :1 AND Date < :2 ORDER BY Date DESC",
                             OneCloud.key(), commonfunction.GetDatetimeFromString(TagDate) )
        Results = Query.fetch(PageSize)
        logging.debug( "--------------------- CollectRecord 1: len(Results) = %d" % (len(Results)) )
        if Results:
            PrePageTag = str(Results[len(Results) - 1].Date)
#    logging.debug( "--------------------- CollectRecord: TagDate = %s, PrePageTag = %s" % (TagDate, PrePageTag) )
            
    #计算下一页起始ID
    Query = db.GqlQuery( "SELECT * FROM CMyCollectTable WHERE HaveCommentOn = True AND CloudKey = :1 ORDER BY Date", OneCloud.key() )
    if 0 < len(TagDate):
        Query = db.GqlQuery( "SELECT * FROM CMyCollectTable WHERE HaveCommentOn = True AND CloudKey = :1 AND Date >= :2 ORDER BY Date",
                             OneCloud.key(), commonfunction.GetDatetimeFromString(TagDate) )
    Results = Query.fetch(PageSize + 1)
#    logging.debug( "--------------------- CollectRecord 2: len(Results) = %d" % (len(Results)) )
    NextPageTag = ''
    if len(Results) == PageSize + 1:
        NextPageTag = str(Results[PageSize].Date)
        Results = Results[:PageSize]

    #修正时间
    for Item in Results:
        Item.Date += TimeDelta

    return Results, PrePageTag, NextPageTag


def GetOneUserOneCloud(UserLoginID, SourceUrl, IsCommend=True):
    if 1 > len(UserLoginID) or 1 > len(SourceUrl):
        return None
    
    OneCloud = GetOneCloudItem(SourceUrl)
    if None == OneCloud:
        return None

    Query = None
    if IsCommend:
        Query = db.GqlQuery("SELECT * FROM CMyCommendTable WHERE CloudKey = :1 AND LoginID = :2", OneCloud.key(), UserLoginID)
    else:
        Query = db.GqlQuery("SELECT * FROM CMyCollectTable WHERE CloudKey = :1 AND LoginID = :2", OneCloud.key(), UserLoginID)
    return Query.get()

#添加一个推荐或收藏
#TagNameString是以 ; 分隔的多个标签
def AddOneMyCloud(SourceUrl, Title, TagNameString, Summary, CommentOn, IsCommend = True):
    User = users.get_current_user()
    if User is None:
        return
    
    if None != GetOneUserOneCloud(User.user_id(), SourceUrl, IsCommend):
        return
    
    TagList = TagNameString.split(";")
    OneCloudKey = SetOneCloudItem(SourceUrl, Title, TagList, Summary, IsCommend)
    if IsCommend:
        MyCommend = googledatabase.CMyCommendTable()
        MyCommend.CloudKey = OneCloudKey
        MyCommend.TagList = TagList
        MyCommend.LoginID = User.user_id()
        MyCommend.LoginAccount = User
        if 0 < len(CommentOn):
            MyCommend.HaveCommentOn = True
            MyCommend.CommentOn = CommentOn
            db.run_in_transaction(function_public.AddOnePropertyCount, OneCloudKey, 'CommentOnNumber', 1)
        else:
            MyCommend.HaveCommentOn = False
        
        MyCommend.put()
    else:
        MyCollect = googledatabase.CMyCollectTable()
        MyCollect.CloudKey = OneCloudKey
        MyCollect.TagList = TagList
        MyCollect.LoginID = User.user_id()
        MyCollect.LoginAccount = User
        if 0 < len(CommentOn):
            MyCollect.HaveCommentOn = True
            MyCollect.CommentOn = CommentOn
            db.run_in_transaction(AddOnePropertyCount, OneCloudKey, 'CommentOnNumber', 1)
        else:
            MyCollect.HaveCommentOn = False
        
        MyCollect.put()
    

def DeleteOneMyCollect(DeleteUrl):
    User = users.get_current_user()
    if User is None:
        return
    
    OneMyCollect == GetOneUserOneCloud(User.user_id(), DeleteUrl, False)
    if None == OneMyCollect:
        return
    
    if OneMyCollect.CloudKey.LastCollect == User:
        OneMyCollect.CloudKey.LastCollect = None
    if OneMyCollect.CloudKey.FirstCollect == User:
        OneMyCollect.CloudKey.FirstCollect = None
        
    db.run_in_transaction(AddOnePropertyCount, OneMyCollect.CloudKey, 'CollectNumber', -1) 
    if OneMyCollect.HaveCommentOn:
        db.run_in_transaction(AddOnePropertyCount, OneMyCollect.CloudKey, 'CommentOnNumber', -1) 
    
    OneMyCollect.delete()
    

#删除一个云，只有管理员才允许
def DeleteOneSystemCloud(DeleteUrl):
    if False == commonfunction.UserIsAdmin():
        return

    OneCloud = GetOneCloudItem(DeleteUrl)
    if None == OneCloud:
        return

    Query = db.GqlQuery("SELECT * FROM CMyCommendTable WHERE CloudKey = :1", OneCloud.key())
    Results = Query.fetch(1000)
    db.delete(Results)

    Query = db.GqlQuery("SELECT * FROM CMyCollectTable WHERE CloudKey = :1", OneCloud.key())
    Results = Query.fetch(1000)
    db.delete(Results)

    DeleteCloudKeyStr = str(OneCloud.key())
    OneCloud.delete()

    if TheItemInMemcacheRecord('CCloudTable_New', DeleteCloudKeyStr):
        #清理缓存区数据
        memcache.delete('CCloudTable_New')
        memcache.delete('CCloudTable_PrePage')
        memcache.delete('CCloudTable_NextPage')




